#include <iostream>
#include <unistd.h>
#include <cstring>
#include <string>
#include <cstdio>
#include <sys/types.h>
#include <sys/wait.h>

#define N 2
#define NUM 1024
using namespace std;

void Write(int wfd)
{
  string s = "hello, i am  child";
  int self = getpid();
  int num = 0;

  char buffer[NUM];
  while (true)
  {
    // buffer[0] = 0;
    // snprintf(buffer, sizeof(buffer), "%s-%d-%d\n", s.c_str(), self, num++);
    // // cout << buffer << endl;

    // write(wfd, buffer, strlen(buffer));
    // sleep(1);
    char c = 'c';
    write(wfd, &c, 1);
    num++;
    cout << num << endl;
    sleep(1);
    if (num > 5)
      break;
  }
}

void Reader(int rfd)
{
  // sleep(50);
  char buffer[NUM];
  while (true)
  {
    buffer[0] = 0;
    ssize_t n = read(rfd, buffer, sizeof(buffer));
    if (n > 0)
    {
      buffer[n] = 0;
      cout << "father get a message[" << getpid() << "]# " << buffer << endl;
    }
    else if (n == 0)
    {
      cout << "father read file done!" << endl;
      break;
      // cout << "n: " << n << endl;
    }
    else
      break;
  }
}

int main()
{
  int pipefd[N] = {0};
  int n = pipe(pipefd);
  if (n < 0)
    return 1;
  // cout << "pipefd[0]: " << pipefd[0] << "pipefd[1]: " << pipefd[1] << endl;
  pid_t id = fork();
  if (id < 0)
    return 2;
  if (id == 0)
  {
    // child
    close(pipefd[0]);

    Write(pipefd[1]);

    close(pipefd[1]);
    exit(0);
  }
  // father
  close(pipefd[1]);

  Reader(pipefd[0]);
  pid_t rid = waitpid(id, nullptr, 0);
  if (rid < 0)
    return 3;

  close(pipefd[0]);

  return 0;
}